package com.scuec.groupfive.Controller;

import com.scuec.groupfive.service.UserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserRegisterController {

    @Autowired
    private UserRegisterService userRegisterService;

    /**
     * 检查用户名是否已存在
     * @param username 要检查的用户名
     * @return 如果用户名存在返回true，否则返回false
     */
    // 访问地址：http://localhost:8080/user/checkUsername
    @GetMapping("/checkUsername")
    public boolean checkUsernameExist(@RequestParam String username) {
        return userRegisterService.isUsernameExist(username);
    }

    /**
     * 注册新用户
     * @param username 用户名
     * @param examYear 考试年份
     * @param password 密码
     * @return 注册成功返回用户ID，失败返回null
     */
    // 访问地址：http://localhost:8080/user/register
    @PostMapping("/register")
    public Integer registerUser(@RequestParam String username,
                                @RequestParam Integer examYear,
                                @RequestParam String password,
                                @RequestParam String phone) {
        return userRegisterService.registerUser(username, examYear, password, phone);
    }

    /**
     * 注册新用户（使用JSON请求体）
     * @param request 包含用户名、考试年份和密码的请求体
     * @return 注册成功返回用户ID，失败返回null
     */
    @PostMapping("/register/json")
    public Integer registerUserWithJson(@RequestBody RegisterRequest request) {
        return userRegisterService.registerUser(
                request.getUsername(),
                request.getExamYear(),
                request.getPassword(),
                request.getPhone()
        );
    }

    // 内部类用于处理JSON请求
    private static class RegisterRequest {
        private String username;
        private Integer examYear;
        private String password;
        private String phone;

        // Getters and Setters
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public Integer getExamYear() {
            return examYear;
        }

        public void setExamYear(Integer examYear) {
            this.examYear = examYear;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }
    }
}